package org.example.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * spring操作redis：提供了两个工具类
 *  StringRedisTemplate:只能操作字符串（java string）
 *  RedisTemplate:可以操作任意类型（java）
 */

@Configuration
public class CacheConfig {
    
    @Resource
    RedisConnectionFactory redisConnectionFactory;
    
    @Bean
    public CacheManager cacheManager() {
        // 创建redis配置
        RedisCacheConfiguration redisCacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofDays(1))// 设置redis缓存时长为一天
                        .serializeValuesWith(
                                RedisSerializationContext.SerializationPair.
                                        fromSerializer(
                                                new GenericJackson2JsonRedisSerializer()
                                        )
                        );
        
        // 创建redis manager
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }
    
    @Bean
    public RedisTemplate<String,Object> redisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //修改序列化数据方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}
